#ifndef ALERTMANAGER_H
#define ALERTMANAGER_H

#include <QWidget>
#include <QSqlTableModel>
#include <QTimer>
#include <QComboBox>
#include <QStyledItemDelegate>

// ✅ 新增前向声明
class DataMonitor;
class Page_control;

namespace Ui {
class AlertManager;
}

class AlertManager : public QWidget
{
    Q_OBJECT

public:
    explicit AlertManager(QWidget *parent = nullptr);
    ~AlertManager();

    void checkAlerts(const QVariantMap& sensorData);
    void setCurrentUserRole(const QString &role);

    // ✅ 新增：设置DataMonitor和Page_control引用
    void setDataMonitor(DataMonitor *dataMonitor);
    void setPageControl(Page_control *pageControl);

signals:
    void alertTriggered(const QString& message);
    void logMessage(const QString &message, const QString &type = "ALARM");

private slots:
    void onAddRule();
    void onDeleteRule();
    void onSaveRules();
    void onAcknowledgeAlert();
    void onResolveAlert();
    void onQueryHistory();
    void onAlertStatusChanged(int index);
    void onRuleFilterChanged();
    void refreshAlerts();
    void onImportRules();
    void onExportRules();
    void onEditRule();

private:
    Ui::AlertManager *ui;
    QSqlTableModel *currentAlertsModel;
    QSqlTableModel *alertHistoryModel;
    QSqlTableModel *alertRulesModel;
    QTimer *alertCheckTimer;

    // ✅ 新增成员变量
    DataMonitor *m_dataMonitor;
    Page_control *m_pageControl;
    QMap<int, int> m_activeAlertsByRule;  // 记录每个规则的活跃告警记录ID

    void setupUI();
    void setupConnections();
    void setupModels();
    void setupAlertCheckTimer();
    bool evaluateAlertCondition(const QString& condition, const QVariantMap& data);
    void triggerAlert(int ruleId, const QVariantMap& sensorData);
    void showAlertDialog(const QString& message);
    void checkDatabaseTables();

    // ✅ 新增：蜂鸣器控制函数
    void activateBuzzer();
    void deactivateBuzzer();

    // ✅ 新增：自动解决告警函数
    void autoResolveAlert(int ruleId, const QVariantMap& sensorData);

    bool importRulesFromIni(const QString& filePath);
    bool exportRulesToIni(const QString& filePath);
    void syncRuleToIni(int ruleId);
    void deleteRuleFromIni(int ruleId);

    QString currentUserRole;
    void applyUserPermissions();

    bool isRuleExists(const QString& deviceId, const QString& description,
                     const QString& condition, const QString& action, const QString& severity);
};

#endif // ALERTMANAGER_H
